package com.igeek.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.igeek.domain.Category;
import com.igeek.domain.Product;
import com.igeek.service.CategoryService;
import com.igeek.utils.ImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author spike
 * @since 2022-01-12
 */
@RestController
@Slf4j
@Api(tags = "使用rest风格处理分类业务")
public class CategoryController {
    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;
    @Autowired
    private CategoryService categoryService;
    //axios.min.js:8 GET http://localhost:8080/forecategory/60?sort=null
    @GetMapping("/forecategory/{cid}")
    @ApiOperation(value = "根据分类id获取分类数据")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "cid",value="分类id",required = true,paramType="path",dataType = "string"),
            @ApiImplicitParam(name = "sort",value = "排序",required = false,paramType = "form",dataType = "string")}
    )
    public Category forecategory(@PathVariable("cid") Integer cid, String sort){
        //1.根据id
        Category category = categoryService.getById(cid);
        //2.填充分类中的产品
        categoryService.fillProduct(category);
        //3.填充产品销量和回复数量
        categoryService.fillSalesAndReviews(category);
        //4.排序sort
        categoryService.sortProduct(category,sort);
        return category;
    }
    //var url = this.uri + "/" + this.bean.id;
    @PutMapping("/categories/{id}")
    //@CachePut(value = "category",key="'admin:*'",condition = "#category.id==#category.id",unless = "#result == null")
    public void updateCategory(Category category,MultipartFile image,HttpServletRequest request) throws IOException {
        //清除缓存
        redisTemplate.delete(redisTemplate.keys("category::admin:*"));
        log.info("updateCategory:"+category);

        //1.修改数据
        categoryService.saveOrUpdate(category);
        //2.修改保存的图片
        if(image == null) return ;
        log.info("image-name:"+image.getOriginalFilename());
        uploadFile(category, image, request);
        return ;

    }

    private void uploadFile(Category category, MultipartFile image, HttpServletRequest request) throws IOException {
        File imageFolder = new File(request.getServletContext().getRealPath("img/category"));
        log.info("path:" + request.getServletContext().getRealPath("img/category"));
        File file = new File(imageFolder, category.getId() + ".jpg");
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        image.transferTo(file);
        BufferedImage img = ImageUtil.change2jpg(file);
        ImageIO.write(img, "jpg", file);
    }

    //根据id获取数据  var url = this.uri + "/" + id;
    @GetMapping("/categories/{id}")
    public Category findById(@PathVariable("id") Integer id){
        Category c = categoryService.getById(id);
        return c;
    }

    //http://localhost:8080/categories?start=0
    @GetMapping("/categories")
    @Cacheable(value = "category",key = "'admin:'+#start+'_'+#size",unless="#result == null")
    public PageInfo<Category> list(@RequestParam(value = "start",required = true,defaultValue = "1") Integer start,
                                   @RequestParam(value = "size",required = true,defaultValue = "5") Integer size){
        PageHelper.startPage(start,size);
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<Category> categories = categoryService.list(wrapper);
        PageInfo<Category> pageInfo = new PageInfo<>(categories);
        log.info("pageInfo:"+pageInfo);
        log.info("categories:"+categories);
        return  pageInfo;
    }

    @PostMapping("/categories")
//    @CachePut(value = "category",condition = "#result!='null'")
    public void addCategory(Category category, MultipartFile image,HttpServletRequest request) throws IOException {
        //清除缓存
        redisTemplate.delete(redisTemplate.keys("category::admin:*"));
        //1.把分类名称保存到数据表
        categoryService.save(category);
        //2.把图片存到服务器
        String filename = image.getOriginalFilename();
        log.info("category:"+category);
        log.info("filename:"+filename);
        uploadFile(category, image, request);
    }

    @DeleteMapping("/categories/{id}")
    //@CacheEvict(value = "category",key = "'admin:*'")//不支持通配符批量删除
    public void deleteCategory(@PathVariable("id") Integer id,HttpServletRequest request){
        //清除缓存
        redisTemplate.delete(redisTemplate.keys("category::admin:*"));
        categoryService.removeById(id);
        //删除本地目录图片
        File imageFolder= new File(request.getServletContext().getRealPath("img/category"));
        File file = new File(imageFolder,id+".jpg");
        if(file.getParentFile().exists()){
            file.delete();
        }
    }

}

